package com.laojiang.imagepickers.ui.grid.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.laojiang.imagepickers.R;
import com.laojiang.imagepickers.data.ImageContants;
import com.laojiang.imagepickers.data.ImageDataModel;
import com.laojiang.imagepickers.data.ImagePickType;
import com.laojiang.imagepickers.data.ImagePickerOptions;
import com.laojiang.imagepickers.data.MediaDataBean;
import com.laojiang.imagepickers.ui.grid.view.IImageDataView;
import com.orhanobut.hawk.Hawk;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 *     author : wxq
 *     time   : 2018/12/11
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class ImageDataRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int ITEM_TYPE_CAMERA = 0x0001;
    private static final int ITEM_TYPE_DATE = 0x0002;
    private static final int ITEM_TYPE_CONTENT = 0x0003;

    private Context mContext;
    private ImagePickerOptions mOptions;

    private IImageDataView mViewImpl;

    private List<MediaDataBean> mDataList = new ArrayList<>();

    public ImageDataRecyclerViewAdapter(Context context, IImageDataView viewImpl) {
        this.mContext = context;
        this.mViewImpl = viewImpl;
        this.mOptions = viewImpl.getOptions();
    }

    public List<MediaDataBean> getDatas() {
        return mDataList;
    }

    public void refreshDatas(List<MediaDataBean> datas) {
        if (datas == null || datas.size() == 0) return;
        mDataList.clear();
        Collections.sort(datas, new Comparator<MediaDataBean>() {
            @Override
            public int compare(MediaDataBean o1, MediaDataBean o2) {
                try {
                    File file1 = new File(o1.getMediaPath());
                    File file2 = new File(o2.getMediaPath());
                    return (int) (file2.lastModified() - file1.lastModified());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
        Map<String, Integer> map = new HashMap<>();
        for (int i = datas.size() - 1; i >= 0; i--) {
            MediaDataBean mediaDataBean = datas.get(i);
            if (TextUtils.isEmpty(mediaDataBean.getMediaPath())) {
                continue;
            }
            File file = new File(mediaDataBean.getMediaPath());
            @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String format = simpleDateFormat.format(new Date(file.lastModified()));
            map.put(format, i);
        }
        List<MediaDataBean> tempList = new ArrayList<>();
        MediaDataBean bean;
        for (String s : map.keySet()) {
            bean = new MediaDataBean();
            bean.date = s;
            bean.item_type = 1;
            bean.index = map.get(s);
            tempList.add(bean);
        }
        Collections.sort(tempList, new Comparator<MediaDataBean>() {
            @Override
            public int compare(MediaDataBean o1, MediaDataBean o2) {
                return o1.index - o2.index;
            }
        });
        for (int i = 0; i < tempList.size(); i++) {
            datas.add(i + tempList.get(i).index, tempList.get(i));
            Log.i("wxq", tempList.get(i).date + "," + tempList.get(i).index);
        }

        mDataList.addAll(datas);
        notifyDataSetChanged();
    }

    @Override
    public int getItemViewType(int position) {
//        if (position == 0 && mOptions.isNeedCamera()) {
//            return ITEM_TYPE_CAMERA;
//        }
        if (mDataList.get(position).item_type == 1) {
            return ITEM_TYPE_DATE;
        }
        return ITEM_TYPE_CONTENT;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == ITEM_TYPE_CAMERA) {
            return new CameraViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_image_data_camera_listitem, parent, false));
        } else if (viewType == ITEM_TYPE_DATE) {
            return new DateViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_image_data_date_listitem, parent, false));
        }
        return new ContentViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_image_data_content_listitem, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
        if (mOptions.isNeedCamera()) {
            i = i - 1;
        }
        if (viewHolder instanceof CameraViewHolder) {
            ((CameraViewHolder) viewHolder).bindViewHolder();
        } else if (viewHolder instanceof ContentViewHolder) {
            ((ContentViewHolder) viewHolder).bindViewHolder(mDataList.get(i), i);
        } else if (viewHolder instanceof DateViewHolder) {
            ((DateViewHolder) viewHolder).bindViewHolder(mDataList.get(i));
        }
    }

    @Override
    public int getItemCount() {
        int count = mDataList.size();
        if (mOptions.isNeedCamera()) {
            count += 1;
        }
        return count;
    }

    class CameraViewHolder extends RecyclerView.ViewHolder {

        TextView tvShow;

        CameraViewHolder(@NonNull View itemView) {
            super(itemView);
            tvShow = itemView.findViewById(R.id.tv_first_text);
        }

        void bindViewHolder() {
            if (mOptions != null && mOptions.isNeedVideo()) {
                tvShow.setText("拍照或者摄像");
            } else {
                tvShow.setText("拍照");
            }
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mViewImpl.startTakePhoto();
                }
            });
        }
    }

    class DateViewHolder extends RecyclerView.ViewHolder {

        TextView dateTv;

        DateViewHolder(@NonNull View itemView) {
            super(itemView);
            dateTv = itemView.findViewById(R.id.item_date_title);
        }

        void bindViewHolder(MediaDataBean bean) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String format = simpleDateFormat.format(new Date());
            if (format.equals(bean.date)) {
                dateTv.setText("今天");
            } else {
                dateTv.setText(bean.date);
            }
        }
    }

    class ContentViewHolder extends RecyclerView.ViewHolder {

        ImageView imgContent;
        View maskView;
        View viewIndicator;

        ContentViewHolder(@NonNull View itemView) {
            super(itemView);
            imgContent = itemView.findViewById(R.id.img_imagepicker_grid_content);
            maskView = itemView.findViewById(R.id.view_imagepicker_mask);
            viewIndicator = itemView.findViewById(R.id.ck_imagepicker_grid_content);
        }

        void bindViewHolder(final MediaDataBean mediaDataBean, final int position) {
            //显示UI
            if (mediaDataBean != null)
                ImageDataModel.getInstance().getDisplayer()
                        .display(itemView.getContext(), mediaDataBean.getMediaPath(), imgContent
                                , R.drawable.glide_default_picture, R.drawable.glide_default_picture
                                , ImageContants.DISPLAY_THUMB_SIZE, ImageContants.DISPLAY_THUMB_SIZE);

            //判断照片还是视频
            int type = mediaDataBean.getType();
            imgContent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mViewImpl != null)
                        mViewImpl.onImageClicked(mediaDataBean, position);
                }
            });

            if (mOptions.getType() == ImagePickType.SINGLE) {
                viewIndicator.setVisibility(View.GONE);
                viewIndicator.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //nothing
                    }
                });
            } else {
                viewIndicator.setVisibility(View.VISIBLE);
                if (ImageDataModel.getInstance().hasDataInResult(mediaDataBean))
                    viewIndicator.setBackgroundResource(R.drawable.ck_imagepicker_grid_selected);
                else
                    viewIndicator.setBackgroundResource(R.drawable.ck_imagepicker_grid_normal);

                viewIndicator.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int curNum = ImageDataModel.getInstance().getResultNum();
                        if (curNum == mOptions.getMaxNum()) {
                            mViewImpl.warningMaxNum();
                        } else if (mediaDataBean.getType() == 0) {
                            if (ImageDataModel.getInstance().hasDataInResult(mediaDataBean))
                                ImageDataModel.getInstance().delDataFromResult(mediaDataBean);
                            else
                                ImageDataModel.getInstance().addDataToResult(mediaDataBean);
//                            int imgSelect = Hawk.get("imgSelect", 0);
//                            if (position > imgSelect) {
                            Hawk.put("imgSelect", position);
//                            }
                            notifyDataSetChanged();
                            mViewImpl.onSelectNumChanged(ImageDataModel.getInstance().getResultNum());
                        }
                    }
                });
            }
            if (type == 1) {
                viewIndicator.setVisibility(View.GONE);
            } else {
                if (mOptions.getType() == ImagePickType.SINGLE)
                    viewIndicator.setVisibility(View.GONE);
                else
                    viewIndicator.setVisibility(View.VISIBLE);
            }
            ArrayList<String> selectImg = Hawk.get("selectImg", new ArrayList<String>());
            try {
                if (selectImg.contains(mediaDataBean.getMediaPath())) {
//                    viewIndicator.setVisibility(View.GONE);
                    maskView.setVisibility(View.VISIBLE);
                    maskView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //nothing
                        }
                    });
                } else {
                    maskView.setVisibility(View.GONE);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
